<template>
  <el-dialog :title="'结账退房'" :close-on-click-modal="false" :visible.sync="visible">
    <el-steps class="closingRoomSteps" :active="stepsCurr" finish-status="success" simple style="margin-bottom: 20px;">
      <el-step title="选择结账房间"></el-step>
      <el-step title="确认结账退房"></el-step>
    </el-steps>

    <el-table style="max-height: 300px;overflow-y: auto;width: 100%" v-if="stepsCurr == 1" ref="multipleTable" :data="unitedHouseList"
      tooltip-effect="dark" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <span style="line-height: 38px;font-size: 16px;font-weight: bold;">同住人</span>
            <el-form-item v-for="(item, index) in props.row.cohabitants" :key="index" style="margin-bottom: 0px;">
              <el-row type="flex" class="row-bg">
                <el-col :span="6">
                  <span>姓名：{{ item.name }}</span>
                </el-col>
                <el-col :span="6">
                  <span>手机号：{{ item.tel }}</span>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="房间">
        <template slot-scope="scope">
          {{ scope.row.roomSign }}{{ scope.row.roomNum }}
          <span class="booking_circle_span orange_color verticalAlignUnset" v-if="scope.row.singleMain == 1" style="margin-left: 4px;">主</span>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="stepsCurr == 1" style="margin-top: 20px;float: right;">
      <el-radio-group v-model="changeType" v-if="changeTypeFlag">
        <el-radio :label="1">单独先结账，费用转到主房</el-radio>
        <el-radio :disabled="unitedHouseSelection.length > 1" :label="2">取消联房，单独结账，费用自付</el-radio>
        <el-radio :disabled="unitedHouseSelection.length > 1" :label="3">全部联房结账</el-radio>
        <!-- <el-radio :label="3"></el-radio> -->
      </el-radio-group>
      <el-button @click="visible = false">{{ $t('Common.Cancel') }}</el-button>
      <el-button @click="next" type="primary" :disabled="unitedHouseSelection.length == 0">{{ $t('Common.Next') }}</el-button>
    </div>

    <el-container v-if="stepsCurr == 2">
      <el-container>
        <el-main style="overflow-y: auto;max-height: 320px;margin-right: 18px;">
          <el-collapse v-model="payTypeList.curr1" @change="handleChange">
            <el-collapse-item v-for="(item, index) in payTypeList.tab1List" :key="index" :title="item.name" :name="item.id">

              <el-row type="flex" class="row-bg" :gutter="20" v-if="item.xieyi == 2 && item.chuzhi == 2 ">
                <el-col :span="7">
<!--                  <el-input-number  size="small" placeholder="金额" :precision="2" :step="100" v-model="item.money" @change="moneyChange(payTypeList.tab1List)">
                    <template slot="prepend">
                      金额
                    </template>

                  </el-input-number> -->
                 <el-input size="small" placeholder="金额" v-model="item.money" @change="moneyChange(payTypeList.tab1List)">
                    <template slot="prepend">
                      金额
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="8">
                  <el-radio-group v-model="item.type" @change="moneyChange(payTypeList.tab1List)" size="small">
                    <el-radio-button :label="1">收款</el-radio-button>
                    <el-radio-button :label="2">退款</el-radio-button>
                    <el-radio-button :label="3">退押金</el-radio-button>
                  </el-radio-group>
                </el-col>
                <el-col :span="4" v-if="item.sb == 1">
                  可退：<span>{{refundableAmount}}</span>
                </el-col>
                <el-col :span="4">
                  <el-button size="small" class="in_block" v-if="item.sb == 2" @click="addPaysItem(item)">添加</el-button>
                </el-col>
              </el-row>

              <!-- 协议单位-->
              <el-row type="flex" class="row-bg" :gutter="20" v-if="item.xieyi == 1" style="margin-bottom: 10px;">
                <el-col :span="10">
                  <el-input size="small" placeholder="金额" :readonly="true" v-model="item.money" @change="moneyChange(payTypeList.tab1List)">

                    <template slot="prepend">
                      金额
                    </template>

                    <template slot="append">
                      <el-button icon="el-icon-search" @click="xieyiMoneySelect(item)" style="border-right: 1px solid #dcdfe6;border-radius: 0;"></el-button>
                      <el-button icon="el-icon-close" @click="xieyiMoneyClose(item,payTypeList.tab1List)"></el-button>
                    </template>

                  </el-input>
                </el-col>
                <el-col :span="12">
                  <el-input size="small" placeholder="协议单位" :readonly="true" v-model="item.customerName" @change="moneyChange(payTypeList.tab1List)">
                    <template slot="prepend">
                      协议单位
                    </template>

                    <template slot="append">
                      <el-button icon="el-icon-search" @click="xieyiXieYiSelect(item)" style="border-right: 1px solid #dcdfe6;border-radius: 0;"></el-button>
                      <el-button icon="el-icon-close" @click="xieyiSelectClose(item)"></el-button>
                    </template>

                  </el-input>
                </el-col>
              </el-row>

              <el-row type="flex" class="row-bg" :gutter="20" v-if="item.xieyi == 1">
                <el-col :span="22">
                  <el-input type="textarea" :rows="2" placeholder="请输入备注" v-model="item.remake">
                  </el-input>
                </el-col>
              </el-row>

              <!-- 储值卡 -->
              <el-row type="flex" class="row-bg" :gutter="20" v-if="item.chuzhi == 1" style="margin-bottom: 10px;">
                <el-col :span="10">
                  <el-input size="small" placeholder="金额" v-model="item.money" @change="moneyChange(payTypeList.tab1List)">

                    <template slot="prepend">
                      金额
                    </template>

                    <template slot="append">
                      <el-button icon="el-icon-search" @click="xieyiMemberSelect(item)" style="border-right: 1px solid #dcdfe6;border-radius: 0;"></el-button>
                      <el-button icon="el-icon-close" @click="xieyiMemberClose(item,payTypeList.tab1List)"></el-button>
                    </template>

                  </el-input>
                </el-col>
              </el-row>

              <el-row type="flex" class="row-bg" :gutter="20" v-if="item.chuzhi == 1 && item.memberEntity.id" style="margin-bottom: 10px;">
                <el-col :span="20">
                  <div class="customerSourceBar" style="margin-bottom: 0;">
                    <div>
                      <div class="in_block">
                        <label class="fourChar">姓名:</label>
                        <label>{{item.memberEntity.name}}</label>
                      </div>
                      <div class="in_block">
                        <label>电话:</label>
                        <label>{{item.memberEntity.tel}}</label>
                      </div>
                      <div class="in_block">
                        <label class="fourChar">级别:</label>
                        <label>{{item.memberEntity.levelName}}</label>
                      </div>
                    </div>
                    <div>
                      <div class="in_block">
                        <label>储值:</label>
                        <label>{{item.memberEntity.totalBalance}}</label>
                      </div>
                      <div class="in_block">
                        <label class="threeChar">积分:</label>
                        <label>{{item.memberEntity.totalScore}}</label>
                      </div>
                      <div class="in_block">
                        <label class="threeChar">卡号:</label>
                        <label>{{item.memberEntity.cardNo}}</label>
                      </div>
                    </div>
                  </div>
                </el-col>



              </el-row>
              <!-- 子集 -->
              <el-row type="flex" style="margin-top: 10px;" class="row-bg" :gutter="20" v-for="(son, sonIndex) in item.sons">
                <el-col :span="7">
                  <el-input size="small" placeholder="金额" v-model="son.money" @change="moneyChange(payTypeList.tab1List)">
                    <template slot="prepend">
                      金额
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="8">
                  <el-radio-group v-model="son.type" @change="moneyChange(payTypeList.tab1List)" size="small">
                    <el-radio-button :label="1">收款</el-radio-button>
                    <el-radio-button :label="2">退款</el-radio-button>
                    <el-radio-button :label="3">退押金</el-radio-button>
                  </el-radio-group>
                </el-col>
                <el-col :span="4">
                  <el-button size="small" class="in_block" @click="remPaysItem(son,item.sons)">删除</el-button>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>

        </el-main>
        <el-aside width="230px">
          <div class="my-line" style="overflow-y: auto;max-height: 60px;width: 98%;">
            <div style="font-size:14px;color:brown;" v-for="(item,index) in info.roomNames">{{item}}</div>
          </div>
          <div class="my-line" style="margin:5px;">
            <div class="box_fl"><label>费用合计：</label></div>
            <div class="box_fr"><label id="lbl-fyhj">{{info.totlPrice}}</label></div>
          </div>
          <div class="my-line" style="margin:5px;">
            <div class="box_fl" style="line-height: 28px;"><label>结账优惠：</label></div>
            <div class="box_fr">
              <el-input size="mini" @change="youhuiInputChange" v-model="dataForm.discountPrice"></el-input>
            </div>
          </div>
          <div class="my-line" style="margin:5px;">
            <div class="box_fl"><label>实际应收：</label></div>
            <div class="box_fr"><label id="lbl-fyhj">{{(info.totlPrice - dataForm.discountPrice).toFixed(2)}}</label></div>
          </div>
          <div class="my-line" style="margin:5px;">
            <div class="box_fl"><label>收款：</label></div>
            <div class="box_fr"><label id="lbl-fyhj">{{info.fukuan.toFixed(2)}}</label></div>
          </div>
          <div class="my-line" style="margin:5px;">
            <div class="box_fl"><label>押金：</label></div>
            <div class="box_fr"><label id="lbl-fyhj">{{info.deposit.toFixed(2)}}</label></div>
          </div>

          <div id="box_jzys" class="my-line" style="color: forestgreen; display: block;">
            <div class="box_fl">
              <label v-if="info.priceCount >= 0">结账应收：</label>
              <label v-if="info.priceCount < 0" style="color: red;">结账应退：</label>
            </div>
            <div class="box_fr"><label id="lbl_jzys">{{Math.abs(info.priceCount).toFixed(2)}}</label></div>
          </div>
          <div id="box_jzys" class="my-line" style="color: red; display: block;margin-top: 0;">
            <div class="box_fl"><label>输入合计：</label></div>
            <div class="box_fr"><label id="lbl_jzys">{{dataForm.inputPrice.toFixed(2)}}</label></div>
          </div>
        </el-aside>
      </el-container>
      <el-footer>
        <el-container>
          <el-main style="overflow-y: auto;max-height: 320px;margin-right: 18px;padding: 0;">
            <el-input type="textarea" :rows="2" placeholder="备注" v-model="dataForm.remarks">
            </el-input>
          </el-main>
          <el-aside width="230px" style="position: relative;">
            <el-checkbox v-model="printJieZhang" style="margin-right: 10px;">打印结账单</el-checkbox>
            <el-button style="bottom: 0;right: 0;" type="primary" icon="el-icon-check" @click="onSubMitBtn">确认结账</el-button>
          </el-aside>
        </el-container>
      </el-footer>
    </el-container>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="请扫描二维码" :visible.sync="payVisible"
      width="30%" append-to-body>
      <div v-loading="payLoding" element-loading-text="正在执行支付">
        <div style="  display: flex;
      justify-content: center;
      align-items: center;margin-bottom:10px">
          <img src="../../../../assets/img/barCode.jpg" />
        </div>

        <div style="text-align:center">支持微信或支付宝条码支付</div>
        <div style="text-align:center">请用条码枪进行扫描</div>
        <span>
          <el-input v-model="auth_no" placeholder="请扫描二维码,支持微信支付宝" @keyup.enter.native="authClose" ref="inputFocus"></el-input>
        </span>
      </div>
    </el-dialog>


    <!-- 设置超时房费 -->
    <el-dialog :close-on-click-modal="false" width="40%" :close-on-press-escape="false" title="设置超时房费" :visible.sync="settingPrice"
      append-to-body>
      <el-form label-width="120px">
        <el-form-item v-for="(item,index) in overtimeList" :label="item.roomSignNum">
          <el-radio-group style="margin-left: 16px;" v-model="item.type" size="small">
            <el-radio-button :label="0">加收半天房费</el-radio-button>
            <el-radio-button :label="1">自定义</el-radio-button>
          </el-radio-group>
          <el-input-number style="margin-left: 16px;" v-show="item.type == 1" size="small" v-model="item.price"
            :precision="2" :step="10" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="overTimeSubmit">确认</el-button>
          <el-button @click="settingPrice = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <agreement v-if="agreementVisible" ref="agreement" @refreClosing="selectXieYiDanWei"></agreement>
    <finance v-if="financeVisible" ref="finance" @refreClosing="moneyChange(payTypeList.tab1List)"></finance>
    <memberleveldetail v-if="memberleveldetailVisible" ref="memberleveldetail" @refreClosing="moneyChange(payTypeList.tab1List)"></memberleveldetail>

  </el-dialog>
</template>

<script>
  import memberleveldetail from './xieyi/hotelmemberleveldetail';
  import agreement from './xieyi/agreement';
  import finance from './xieyi/finance';
  export default {
    data() {
      return {
        sbEntity: {

        },
        overtimeList: [],
        overtimePrice: 0,
        overtimeFlag: false,
        memberleveldetailVisible: false,
        settingPrice: false,
        financeVisible: false,
        agreementVisible: false,
        printJieZhang: false,
        refundableAmountVisible: false,
        refundableAmount: 0,
        changeTypeFlag: true,
        payLoding: false,
        // 1 转账到主房 2解除联房，费用自付
        changeType: 1,
        unitedHouseList: [],
        unitedHouseSelection: [],
        unitedHouseSelectionId: [],
        stepsCurr: 1,
        tabs: {
          curr: 'first',
          tab1Money: 0.0,
          tab2Money: 0.0,
          tab3Money: 0.0
        },
        dataForm: {
          inputPrice: 0,
          discountPrice: 0,
          remarks: '',
        },
        info: {
          totlPrice: 0,
          xykysq: 0,
          priceCount: 0,
          deposit: 0,
          fukuan: 0,
          roomPrice: 0,
          totlxfPrice: 0,
          xiaofei: 0,
          roomNames: [],
        },
        payTypeList: {
          tab1List: [],
          tab2List: [],
          tab3List: [],
          curr1: [],
          curr2: [],
          curr3: []
        },
        curr: '',
        visible: false,
        item: {},
        mainCheck: false,
        payInterfaceConfig: {}, //支付
        payVisible: false,
        auth_no: ''
      };
    },
    components: {
      agreement,
      finance,
      memberleveldetail
    },
    methods: {
      overTimeSubmit() {
        this.overtimePrice = 0;
        // this.overtimeList.forEach(item => {
        //   if(item.overtime){
        //     if(item.type == 0){
        //       console.log(item.todayRoomPrice)
        //       this.overtimePrice = this.overtimePrice + (item.todayRoomPrice / 2)
        //     }else if(item.type == 1){
        //       this.overtimePrice = this.overtimePrice + parseFloat(item.price)
        //     }
        //   }
        // })
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinaccounting/united_setting_price`),
          method: 'post',
          data: this.$http.adornData({
            overtimeList: JSON.stringify(this.overtimeList),
            overtimeFlag: this.overtimeFlag ? 1 : 2,
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log("超时总设置费用", this.overtimePrice)
            this.settingPrice = false
            this.next3()
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      selectXieYiDanWei() {

      },
      xieyiMoneySelect(item) {
        this.financeVisible = true;
        this.$nextTick(() => {
          this.$refs.finance.init(item, this.unitedHouseSelectionId)
        })
      },
      xieyiMemberSelect(item) {
        this.memberleveldetailVisible = true;
        this.$nextTick(() => {
          this.$refs.memberleveldetail.init(item)
        })
      },
      xieyiXieYiSelect(item) {
        this.agreementVisible = true;
        this.$nextTick(() => {
          this.$refs.agreement.init(item)
        })
      },
      xieyiMoneyClose(item, list) {
        item.money = 0;
        this.moneyChange(list);
      },
      xieyiMemberClose(item, list) {
        item.money = 0;
        item.memberEntity.id = ''
        item.memberEntity.name = ''
        item.memberEntity.tel = ''
        item.memberEntity.levelName = ''
        item.memberEntity.totalBalance = ''
        item.memberEntity.totalScore = ''
        item.memberEntity.cardNo = ''
        this.moneyChange(list);
      },
      xieyiSelectClose(item) {
        item.customerId = "";
        item.customerName = "";
      },
      addPaysItem(payItem) {
        payItem.sons.push({
          ...payItem,
          sysType: payItem.type,
          money: 0,
          type: 1,
        })
      },
      remPaysItem(sonInfo, sonsArr) {
        sonsArr.splice(sonsArr.indexOf(sonInfo), 1);
        this.moneyChange(this.payTypeList.tab1List);
      },
      init(item) {
        Object.assign(this.$data, this.$options.data());
        this.$nextTick(() => {
          this.visible = true;
          this.item = item;
          console.log("item", item)

          this.getRoomList();
          this.getPayInterface();
          if (this.$cookie.get('printJieZhang') != null) {
            if (this.$cookie.get('printJieZhang') == 1) {
              this.printJieZhang = true
            } else {
              this.printJieZhang = false
            }
          }
        })
      },
      getPayInterface() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelsellerpayinterfaceconfig/myInfo`),
          method: 'get'
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.payInterfaceConfig = data.tHotelSellerPayInterfaceConfig
          } else {
            this.$message.error("加载支付配置失败")
          }
        })
      },
      async next() {
        await this.next1();
      },
      async next1() {
        //勾上住房间就不能结账
        if (this.mainCheck) {
          //是否勾选全部联房结账
          if (this.changeType != 3) {
            this.$alert('其他联房未结账，不可勾选主房', '提示', {
              confirmButtonText: '确定',
              callback: action => {

              }
            });
            return false
          }

        }
        var arr = [];
        this.unitedHouseSelection.forEach(item => {
          arr.push(item.id)
        })
        this.unitedHouseSelectionId = arr;
        console.log(this.unitedHouseSelectionId)
        //全选 常规结账
        if (!this.changeTypeFlag) {
          this.changeType = 4
        }
        if (this.changeType == 3) {
          this.jzId = this.unitedHouseSelection[0].id
          //全选房间
          var arr = [];
          this.unitedHouseList.forEach(item => {
            arr.push(item.id)
          })
          this.unitedHouseSelectionId = arr;
        }
        if (this.changeType == 2) {
          this.jzId = this.unitedHouseSelection[0].id
        }

        this.overtimeList = [];
        //循环判定是否存在超时房间
        this.unitedHouseList.forEach(item => {
          console.log(item.overtime)
          if (item.overtime) {
            console.log(this.unitedHouseSelectionId.findIndex(obj => obj == item.id))
            if (this.unitedHouseSelectionId.findIndex(obj => obj == item.id) >= 0) {
              this.overtimeList.push({
                mainPeopleId: item.mainPeopleId,
                floorRoomId: item.id,
                roomSignNum: item.roomSignNum,
                overtime: item.overtime,
                todayRoomPrice: item.todayRoomPrice,
                type: 0,
                price: 0
              })
            }
          }
        })
        console.log(this.overtimeList)
        if (this.overtimeList.length > 0) {
          this.peintOvertime();
          return false;
        } else {
          this.next3();
        }
      },
      next3() {
        //判断结账状态值
        var changeType = this.changeType
        //单独结账，费用转到主房，状态值更改为联房退房
        if (changeType == 1 && this.changeTypeFlag) {
          //发起请求，转移房费
          this.$confirm('是否该房间单独先结账，并将该房间的全部费用转到主房间，由主房间结账?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinaccounting/check_out`),
              method: 'post',
              data: this.$http.adornData({
                roomIds: this.unitedHouseSelectionId.join(","),
                singleId: this.item.singleId,
                overtimeList: JSON.stringify(this.overtimeList),
                overtimeFlag: this.overtimeFlag ? 1 : 2,
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.visible = false
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.$nextTick(() => {
                      this.$emit('refreClosing')

                    });
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          })
        } else {
          this.stepsCurr = 2;
          this.getPayTypes();

        }
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      //获取结账房间列表
      getRoomList() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinsingle/united_house_list/${this.item.singleId}`),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.unitedHouseList = data.data;
            //只有一个直接结账
            if (data.data.length == 1) {
              this.unitedHouseSelection = this.unitedHouseList
              //正常流程
              this.changeType = 4
              this.next()
            }
            //自动勾选当前房间
            for (var i = 0; i < this.unitedHouseList.length; i++) {
              if (this.unitedHouseList[i].id == this.item.floorRoomId) {
                this.toggleSelection([this.unitedHouseList[i]])
                break
              }
            }
          }
        });
      },
      //弹框，告知要加收房费
      peintOvertime() {
        this.$confirm('选中房间已经超过中午退房时间是否加收房费?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.overtimeFlag = true;
          this.settingPrice = true;
        }).catch(() => {
          this.overtimeFlag = false
          this.next3();
        })
      },
      //选择结账房间
      async handleSelectionChange(val) {
        this.unitedHouseSelection = val;
        if (this.unitedHouseSelection.length == this.unitedHouseList.length) {
          this.changeTypeFlag = false
        } else {
          this.changeTypeFlag = true
        }
        this.mainCheck = false;
        if (this.unitedHouseSelection.length != this.unitedHouseList.length) {
          this.unitedHouseSelection.forEach(item => {
            console.log(item)
            if (this.unitedHouseList.filter(f => f.id == item.id).length > 0 && this.unitedHouseList.filter(f =>
                f.id == item.id)[0].singleMain == 1) {
              this.mainCheck = true;
              console.log(this.mainCheck)
            }
          })
        }
        console.log(val);
      },
      handleChange(val) {
        console.log(val);
      },
      getRoomPrice() {},
      moneyChange(list) {
        var currMoney = 0;
        var currMoney1 = 0;
        var currMoney2 = 0;
        list.forEach(item => {
          if(!item.money){
            item.money = 0;
          }
          if (item.type == 1) {
            currMoney += parseFloat(item.money);
          } else if (item.type == 2) {
            currMoney1 += parseFloat(item.money);
          } else {
            currMoney2 += parseFloat(item.money);
          }
          if (item.sons.length > 0) {
            item.sons.forEach(son => {
              if (son.type == 1) {
                currMoney += parseFloat(son.money);
              } else if (son.type == 2) {
                currMoney1 += parseFloat(son.money);
              } else {
                currMoney2 += parseFloat(son.money);
              }
            })
          }
        });
        //收款
        this.tabs.tab1Money = currMoney;
        //退款
        this.tabs.tab2Money = currMoney1;
        //退押金
        this.tabs.tab3Money = currMoney2;
        //计算本次输入金额的合
        this.dataForm.inputPrice = currMoney - currMoney1 - currMoney2
      },
      youhuiInputChange() {
        this.info.priceCount = this.info.roomPrice + this.info.xiaofei - (this.info.fukuan + this.info.deposit) -
          parseFloat(this.dataForm.discountPrice)
        console.log(this.payTypeList.tab1List)
        var entity = this.payTypeList.tab1List.filter(item => item.sysType == 4)[0]
        console.log("改成价格")
        console.log(entity)
        if (this.info.priceCount > 0) {
          entity.money = this.info.priceCount.toFixed(2)
        } else {
          entity.money = Math.abs(this.info.priceCount).toFixed(2)
          entity.type = 2
        }
        this.moneyChange(this.payTypeList.tab1List);
      },
      //获取支付方式
      getPayTypes() {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroompaytype/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: 1,
            limit: 999,
            isClosing: 1,
            state: 1,
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            var arr = []
            data.page.list.forEach(item => {
              arr.push(item.id)
            })
            this.payTypeList.curr1 = arr
            // type 1收款 2退款 3退押金
            this.payTypeList.tab1List = data.page.list.map(item => ({
              ...item,
              sysType: item.type,
              money: 0,
              type: 1,
              sons: []
            }));

            var newArr = [];
            this.payTypeList.tab1List.forEach(item => {
              if (item.sb == 2) {
                newArr.push({
                  ...item
                })
              } else {
                this.sbEntity = item;
              }
            })

            this.$nextTick(() => {
              setTimeout(() => {
                this.getInfo();
              }, 10)
            });
          }
        });
      },
      //查询扫呗预授权金额
      getsbMoney() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinpeople/view_ysq_money_all`),
          method: 'get',
          params: this.$http.adornParams({
            roomIds: this.unitedHouseSelectionId.join(","),
            singleId: this.item.singleId
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.refundableAmount = data.money
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      //查询用户房型明细
      getInfo() {
        this.$nextTick(() => {
          this.getsbMoney()
          console.log(this.payTypeList.tab1List)
          //现金
          var entity = this.payTypeList.tab1List.filter(item => item.sysType == 4)[0]
          //协议单位
          var xieyientity = this.payTypeList.tab1List.filter(item => item.sysType == 5)[0]
          //会员
          var memberentity = this.payTypeList.tab1List.filter(item => item.sysType == 6)[0]




          this.$http({
            url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinaccounting/info_detailed`),
            method: 'post',
            params: this.$http.adornParams({
              singleId: this.item.singleId,
              ids: this.unitedHouseSelectionId.join(",")
            })
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              if (this.overtimeFlag) {
                data.data.roomPrice += this.overtimePrice
              }
              this.info.xykysq = data.data.xykysq
              this.info.deposit = data.data.deposit
              this.info.fukuan = data.data.fukuan
              this.info.roomPrice = data.data.roomPrice
              this.info.xiaofei = data.data.xiaofei
              this.info.roomNames = data.data.roomNames
              //负数则退款 正数则付款
              this.info.priceCount = data.data.roomPrice + data.data.xiaofei - (data.data.fukuan + data.data.deposit)
              this.info.totlPrice = data.data.roomPrice + data.data.xiaofei
              if (data.data.sourceType == 2) {
                xieyientity.customerId = data.data.agreementEntity.id;
                xieyientity.customerName = data.data.agreementEntity.customerName;
              }
              if (data.data.sourceType == 1) {
                memberentity.memberEntity.id = data.data.memberEntity.id
                memberentity.memberEntity.name = data.data.memberEntity.name
                memberentity.memberEntity.tel = data.data.memberEntity.tel
                memberentity.memberEntity.levelName = data.data.memberEntity.levelName
                memberentity.memberEntity.totalBalance = data.data.memberEntity.totalBalance
                memberentity.memberEntity.totalScore = data.data.memberEntity.totalScore
                memberentity.memberEntity.cardNo = data.data.memberEntity.cardNo
              }
              console.log(entity)
              if (this.info.deposit <= 0) {
                if (data.data.sourceType == 1) {
                  memberentity.money = data.data.roomPrice + data.data.xiaofei

                  if (data.data.fukuan + data.data.deposit > 0) {
                    entity.money = Math.abs(data.data.fukuan + data.data.deposit)
                    entity.type = 2
                  } else {
                    entity.money = Math.abs(data.data.fukuan + data.data.deposit)
                  }
                } else if (data.data.sourceType == 2) {
                  xieyientity.money = data.data.roomPrice + data.data.xiaofei

                  if (data.data.fukuan + data.data.deposit > 0) {
                    entity.money = Math.abs(data.data.fukuan + data.data.deposit)
                    entity.type = 2
                  } else {
                    entity.money = Math.abs(data.data.fukuan + data.data.deposit)
                  }
                } else {
                  if (data.data.fukuan + data.data.deposit - (data.data.roomPrice + data.data.xiaofei) >= 0) {
                    entity.money = Math.abs(data.data.fukuan + data.data.deposit - (data.data.roomPrice + data.data
                      .xiaofei))
                    entity.type = 2
                  } else {
                    entity.money = Math.abs(data.data.fukuan + data.data.deposit - (data.data.roomPrice + data.data
                      .xiaofei))
                  }
                }
              } else {
                //优先退押金。
                entity.money = this.info.deposit
                entity.type = 3
                if (data.data.sourceType == 1) {
                  memberentity.money = data.data.roomPrice + data.data.xiaofei

                  if (data.data.fukuan > 0) {
                    //其他资金操作
                    entity.sons.push({
                      ...entity,
                      sysType: entity.type,
                      money: 0,
                      type: 1,
                    })
                    var son = entity.sons[0]
                    son.money = Math.abs(data.data.fukuan)
                    son.type = 2
                  } else if (data.data.fukuan - (data.data.roomPrice + data.data.xiaofei) == 0) {

                  } else {
                    //其他资金操作
                    entity.sons.push({
                      ...entity,
                      sysType: entity.type,
                      money: 0,
                      type: 1,
                    })
                    var son = entity.sons[0]
                    son.money = Math.abs(data.data.fukuan)
                  }
                } else if (data.data.sourceType == 2) {
                  xieyientity.money = data.data.roomPrice + data.data.xiaofei

                  if (data.data.fukuan > 0) {
                    //其他资金操作
                    entity.sons.push({
                      ...entity,
                      sysType: entity.type,
                      money: 0,
                      type: 1,
                    })
                    var son = entity.sons[0]

                    son.money = Math.abs(data.data.fukuan)
                    son.type = 2
                  } else if (data.data.fukuan - (data.data.roomPrice + data.data.xiaofei) == 0) {

                  } else {
                    //其他资金操作
                    entity.sons.push({
                      ...entity,
                      sysType: entity.type,
                      money: 0,
                      type: 1,
                    })
                    var son = entity.sons[0]
                    son.money = Math.abs(data.data.fukuan)
                  }
                } else {
                  if (data.data.fukuan - (data.data.roomPrice + data.data.xiaofei) > 0) {
                    //其他资金操作
                    entity.sons.push({
                      ...entity,
                      sysType: entity.type,
                      money: 0,
                      type: 1,
                    })
                    var son = entity.sons[0]
                    son.money = Math.abs(data.data.fukuan - (data.data.roomPrice + data.data.xiaofei))
                    son.type = 2
                  } else if (data.data.fukuan - (data.data.roomPrice + data.data.xiaofei) == 0) {

                  } else {
                    //其他资金操作
                    entity.sons.push({
                      ...entity,
                      sysType: entity.type,
                      money: 0,
                      type: 1,
                    })
                    var son = entity.sons[0]
                    son.money = Math.abs(data.data.fukuan - (data.data.roomPrice + data.data.xiaofei))
                  }
                }

              }

              this.moneyChange(this.payTypeList.tab1List);
            }
          });

        })
      },
      //结账
      onSubMitBtn() {
        var printState = 2;
        if (this.printJieZhang) {
          printState = 1
          this.$cookie.set('printJieZhang', 1)
        } else {
          this.$cookie.set('printJieZhang', 2)
        }
        var arr = []
        for (var i = 0; i < this.payTypeList.tab1List.length; i++) {
          var item = this.payTypeList.tab1List[i];
          if (item.money != 0) {
            if (item.xieyi == 1) {
              console.log(!item.customerName)
              console.log(item.customerName)
              if (!item.customerName) {
                this.$message.error("操作失败：请选择协议单位");
                return
              }
              console.log(!item.customerId)
              if (!item.customerId) {
                this.$message.error("操作失败：请选择协议单位");
                return
              }
            }
            if (item.chuzhi == 1) {
              if (!item.memberEntity.id) {
                this.$message.error("操作失败：请选择会员");
                return
              }
            }
            arr.push({
              money: item.money,
              type: item.type,
              id: item.id,
              sb: item.sb,
              remake: item.remake == null ? "" : item.remake,
              xieyi: item.xieyi,
              chuzhi: item.chuzhi,
              customerId: item.customerId,
              memberId: item.memberEntity.id + ""
            })
          }
          if (item.sons.length > 0) {
            item.sons.forEach(son => {
              if (son.money != 0) {
                arr.push({
                  money: son.money,
                  type: son.type,
                  id: son.id,
                  sb: item.sb,
                })
              }
            })
          }
        }
        //对比输入是否正确
        console.log("输入金额"+ this.dataForm.inputPrice.toFixed(2))
        console.log("实际金额"+ this.info.priceCount.toFixed(2))
        if (this.dataForm.inputPrice.toFixed(2) != this.info.priceCount.toFixed(2)) {
          this.$message.error("操作失败：本次输入必须等于结账应收");
          return false
        }

        if (this.payInterfaceConfig.switchConfig == 1) {
          //触发
          if (this.sbEntity.money > 0) {
            if (this.sbEntity.type == 1) {
              this.payVisible = true;
              this.changeFocus();
              return
            } else {
              if (this.sbEntity.money > this.refundableAmount) {
                this.$message.error("退款金额不可超过已授权可退金额")
                return
              } else {

              }
            }
          }
        }
        console.log(JSON.stringify(arr))
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinaccounting/united_house`),
          method: 'post',
          data: this.$http.adornData({
            xfMoney: (this.info.totlPrice - this.dataForm.discountPrice).toFixed(2),
            subType: 2,
            singleId: this.item.singleId,
            floorRoomIds: JSON.stringify(this.unitedHouseSelectionId),
            prices: JSON.stringify(arr),
            inputPrice: this.dataForm.inputPrice,
            discountPrice: this.dataForm.discountPrice,
            remarks: this.dataForm.remarks,
            changeType: this.changeType,
            overtimeList: JSON.stringify(this.overtimeList),
            overtimeFlag: this.overtimeFlag ? 1 : 2,
            floorRoomId: this.jzId
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.visible = false
            this.$nextTick(() => {
              this.$emit('refreClosing')
              this.$emit('refreshDataList')
              this.$emit('refrePrintJieZhang', printState, this.item.singleId)
            });
            this.$message({
              message: this.$t('Common.OperationSuccessful'),
              type: 'success',
              duration: 1500,
              onClose: () => {

              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      changeFocus() {
        this.$nextTick(() => {
          this.$refs.inputFocus.focus();
        })
      },
      authClose() {
        // this.payVisible = false;
        this.payLoding = true;
        //扫码支付请求数据
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/preAuthBar'),
          method: 'post',
          data: this.$http.adornData({
            'type': 2, //正式
            'auth_no': this.auth_no, //授权码，客户的付款码
            'total_fee': this.sbEntity.money * 100, //金额，单位分
            'order_body': '结账退房', //订单描述
            'attach': '结账退房', //附加数据,原样返回
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.payVisible = false
            //保存入账信息
            this.auth_no = "";
            this.payLoding = false;
            var terminalTrace = data.data.terminalTrace
            this.authSubForm(terminalTrace);
          } else if (data.code == 3) {
            //循环查询订单，直至成功或失败
            this.timer = setInterval(() => {
              this.queryOrder(data.data);
            }, 1500);
          } else {
            this.payLoding = false;
            this.auth_no = "";
            this.payVisible = false
            this.$message.error(data.msg);
          }
        })
      },
      queryOrder(data) {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/commonQuery'),
          method: 'post',
          data: this.$http.adornData({
            'pay_type': data.payType,
            'terminal_trace': data.terminalTrace,
            'terminal_time': data.terminalTime,
            'out_trade_no': data.outTradeNo,
          })
        }).then(({
          data
        }) => {
          console.log(data)
          if (data && data.code === 0) {
            clearInterval(this.timer)
            this.payLoding = false;
            console.log(data)
            this.payVisible = false
            this.auth_no = "";
            //保存入账信息
            var terminalTrace = data.data.terminalTrace
            this.authSubForm(terminalTrace);
          } else if (data.code === 3) {

          } else {
            clearInterval(this.timer)
            this.payLoding = false;
            this.payVisible = false
            this.auth_no = "";
            this.$message.error(data.msg);
          }
        })
      },
      authSubForm(terminalTrace) {
        var arr = []
        this.payTypeList.tab1List.forEach(item => {
          if (item.money != 0) {
            arr.push({
              money: item.money,
              type: item.type,
              id: item.id,
              sb: item.sb,
            })
          }
          if (item.sons.length > 0) {
            item.sons.forEach(son => {
              if (son.money != 0) {
                arr.push({
                  money: son.money,
                  type: son.type,
                  id: son.id,
                  sb: item.sb,
                })
              }
            })
          }
        });
        let _this = this
        setTimeout(function() {

          _this.$http({
            url: _this.$http.adornUrl(`/hotel/thotelfloorroomcheckinaccounting/united_house`),
            method: 'post',
            data: _this.$http.adornData({
              subType: 1,
              singleId: _this.item.singleId,
              terminalTrace: terminalTrace,
              floorRoomIds: JSON.stringify(_this.unitedHouseSelectionId),
              prices: JSON.stringify(arr),
              inputPrice: _this.dataForm.inputPrice,
              discountPrice: _this.dataForm.discountPrice,
              remarks: _this.dataForm.remarks,
              changeType: _this.changeType,
              overtimeList: JSON.stringify(_this.overtimeList),
              overtimeFlag: _this.overtimeFlag ? 1 : 2,
              floorRoomId: _this.jzId
            })
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              _this.visible = false
              _this.$message({
                message: _this.$t('Common.OperationSuccessful'),
                type: 'success',
                duration: 1500,
                onClose: () => {
                  _this.$nextTick(() => {
                    _this.$emit('refreClosing')
                  });
                }
              });
            } else {
              _this.$message.error(data.msg);
            }
          });

        }, 1000);

      },
    }
  };
</script>

<style lang="scss" scoped>
  .closingRoomSteps .el-step.is-simple .el-step__head {
    display: inherit;
  }

  .my-line {
    margin: 10px 5px;
    float: left;
  }

  .box_fl {
    position: relative;
    width: 109px;
    float: left;
    font-size: 16px;
  }

  .box_fr {
    position: relative;
    width: 109px;
    float: right;
    font-size: 16px;
    text-align: right;
    padding-right: 12px;
  }

  body>div.el-dialog__wrapper>div>div.el-dialog__body>section>section>aside div.box_fr>div>input {
    text-align: right;
  }

  .booking_circle_span,
  .orange_circle_span {
    display: inline-block;
    vertical-align: middle;
  }

  .booking_circle_span {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    color: #f24e4c;
    border: 1px solid #f24e4c;
    font-size: 12px;
    text-align: center;
    line-height: 16px;
  }

  .customerSourceBar {
    padding: 8px 16px;
  }

  .customerSourceBar>div>.in_block:nth-of-type(2) {
    width: 37%;
  }

  .customerSourceBar>div>.in_block:first-of-type {
    width: 26%;
  }

  .in_block {
    display: inline-block;
  }

  .el-dialog__wrapper /deep/ .el-dialog {
    width: 70%;

    .el-footer {
      padding-right: 0;
    }

    /deep/ .el-aside {
      white-space: nowrap;
    }
  }

  @media only screen and (max-width: 1180px) {
    .el-dialog__wrapper /deep/ .el-dialog {
      width: 100%;
    }
  }
</style>
